﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Orchard.Security;
using Orchard;
using Orchard.ContentManagement;
using Orchard.Users.Services;
using Orchard.Users.Models;
using Orchard.Contrib.ShapeMessaging.Services;
using Orchard.Localization;
using Orchard.Users.Events;
using Orchard.UI.Notify;
using Contrib.Mod.RegistrationProviders.Models;

namespace Contrib.Mod.ResetPassword.Services
{
    public interface IResetService : IDependency
    {
        bool SendPasswordResetLink(string usernameOrEmail, Func<string, string> createUrl);
    }

    public class ResetService : IResetService
    {
        private readonly IContentManager contentManager;
        private readonly IUserService userService;
        private readonly IOrchardServices orchardServices;
        private readonly IShapeMessagingService shapeMessagingService;
        private static readonly TimeSpan DelayToResetPassword = new TimeSpan(1, 0, 0, 0);

        public ResetService(IContentManager contentManager, 
            IUserService userService, 
            IOrchardServices orchardServices,
            IShapeMessagingService shapeMessagingService)
        {
            this.userService = userService;
            this.contentManager = contentManager;
            this.orchardServices = orchardServices;
            this.shapeMessagingService = shapeMessagingService;
            T = NullLocalizer.Instance;
        }

        //public IOrchardServices orchardServices { get; private set; }

        public Localizer T { get; set; }

        public bool SendPasswordResetLink(string usernameOrEmail, Func<string, string> createUrl)
        {
            var lowerName = usernameOrEmail.ToLowerInvariant();
            var user = contentManager.Query<UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName || u.Email == lowerName).List().FirstOrDefault();

            if (user != null)
            {
                string nonce = userService.CreateNonce(user, DelayToResetPassword);
                string url = createUrl(nonce);

                //_messageManager.Send(user.ContentItem.Record, MessageTypes.LostPassword, "email", new Dictionary<string, string> { { "LostPasswordUrl", url } });
                try
                {
                    dynamic shape = orchardServices.New.ResetEmail();

                    shape.User = user;
                    shape.Site = this.orchardServices.WorkContext.CurrentSite;
                    //shape.Site = this.Services.WorkContext.CurrentSite;
                    //shape.Title = title;
                    //shape.Subject = title;
                    shape.Url = url;

                    //TODO: Add site name to subject
                    shapeMessagingService.Send(user, shape, T("Password Reset").ToString());
                    return true;
                }
                catch (Exception e)
                {
                    return false;
                }


            }

            return false;
        }

        //public bool SendPasswordResetLink(string usernameOrEmail, Func<string, string> createUrl)
        //{
        //    var lowerName = usernameOrEmail.ToLowerInvariant();
        //    var user = contentManager.Query<UserPart, UserPartRecord>().Where(u => u.NormalizedUserName == lowerName || u.Email == lowerName).List().FirstOrDefault();

        //    if (user != null)
        //    {
        //        string nonce = userService.CreateNonce(user, DelayToResetPassword);
        //        string url = createUrl(nonce);

        //        //_messageManager.Send(user.ContentItem.Record, MessageTypes.LostPassword, "email", new Dictionary<string, string> { { "LostPasswordUrl", url } });

        //        Email(user, url);
                
        //    }

        //    return false;
        //}

        //public void Email(UserPart user, string url)
        //{
        //    try
        //    {
        //        dynamic shape = orchardServices.New.ResetEmail(ViewModel: user);
                    
        //        shape.User = user;
        //        shape.Site = this.orchardServices.WorkContext.CurrentSite;
        //        //shape.Site = this.Services.WorkContext.CurrentSite;
        //        //shape.Title = title;
        //        //shape.Subject = title;
        //        shape.Url = url;

        //        //TODO: Add site name to subject
        //        shapeMessagingService.Send(user, shape, T("Password Reset").ToString());
                    
        //    }
        //    catch (Exception e)
        //    {
                    
        //    }
        //}
    }






    public class MailingUserEventHandler : IUserEventHandler
    {
        
        private readonly IShapeMessagingService shapeMessagingService;

        private readonly INotifier notifier;

        public MailingUserEventHandler(
            
            IShapeMessagingService shapeMessagingService,
            IOrchardServices services,
            INotifier notifier)
        {
            this.notifier = notifier;
            this.shapeMessagingService = shapeMessagingService;
            this.Services = services;
            

            this.T = NullLocalizer.Instance;
        }

        public IOrchardServices Services { get; private set; }

        public Localizer T { get; set; }

        public void Creating(UserContext context)
        {
        }

        public void Created(UserContext context)
        {
            var registrationSettings = Services.WorkContext.CurrentSite.As<RegistrationSitePart>();

            if (!registrationSettings.SendRegistrationEmail.GetValueOrDefault())
                return;

            var userPart = context.User.ContentItem; // u.ContentItem;
            var props = new Dictionary<string, string>();

            props.Add("Title", "Thank you for registering");
            props.Add("Subject", "Thank you for registering");

            string title = T("Thank you for registering").ToString();
            try
            {
                dynamic shape = Services.New.CreatedUser(ViewModel: userPart);

                shape.User = userPart;
                shape.Site = this.Services.WorkContext.CurrentSite;
                shape.Title = title;
                shape.Subject = title;

                shapeMessagingService.Send(userPart, shape, T("Thank you for registering").ToString());
            }
            catch (Exception e)
            {
                this.notifier.Warning(T("There has been a problem sending your email."));
            }
        }

        public void LoggedIn(Orchard.Security.IUser user)
        { }

        public void LoggedOut(Orchard.Security.IUser user)
        { }

        public void AccessDenied(Orchard.Security.IUser user)
        { }

        public void ChangedPassword(Orchard.Security.IUser user)
        { }

        public void SentChallengeEmail(Orchard.Security.IUser user)
        { }

        public void ConfirmedEmail(Orchard.Security.IUser user)
        { }

        public void Approved(Orchard.Security.IUser user)
        { }


    }
}